package com.wwk.phone.service.impl;

import com.wwk.phone.dao.BookDao;
import com.wwk.phone.entity.Book;
import com.wwk.phone.entity.vo.BookQuery;
import com.wwk.phone.service.BookService;
import com.wwk.phone.utils.R;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * (TBook)表服务实现类
 *
 * @author makejava
 * @since 2023-06-08 13:07:59
 */
@Service
public class BookServiceImpl implements BookService {
    @Resource
    private BookDao bookDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Book queryById(Long id) {
        return this.bookDao.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param book 实例对象
     * @return 实例对象
     */
    @Override
    public boolean insert(Book book) {
        book.setShield(0);
        book.setCreateTime(new Date());
        book.setUpdateTime(new Date());
        return this.bookDao.insert(book) > 0;
    }

    /**
     * 修改数据
     *
     * @param Book 实例对象
     * @return 实例对象
     */
    @Override
    public Book update(Book Book) {
        this.bookDao.update(Book);
        return this.queryById(Book.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.bookDao.deleteById(id) > 0;
    }

    @Override
    public List<Book> queryBooksByUserId(String userId) {
        return bookDao.queryFriendsByUserId(userId);
    }

    @Override
    public R pageFriendCondition(Long current, Long limit, BookQuery bookQuery, String userId) {
        long total = 0;
        List<Book> list = bookDao.queryFriendCondition((current - 1) * limit, limit, userId, bookQuery);
        total = list.size();
        //shield为0或者null,都直接查询所有用户
        if (StringUtils.isEmpty(bookQuery.getPhone())
                && StringUtils.isEmpty(bookQuery.getSex())
                && (StringUtils.isEmpty(bookQuery.getShield()) || bookQuery.getShield() == 0)) {
            //如果没有查询条件，则total为总数
            Book book = new Book();
            book.setUserId(userId);
            book.setShield(0);
            total = bookDao.count(book);
        }
        return R.ok().data("rows", list).data("total", total);
    }

    @Override
    public boolean shieldFriend(Long friendId) {
        Book book = queryById(friendId);
        book.setShield(1);
        return update(book)!= null;
    }

    @Override
    public boolean recoveryFriend(Long friendId) {
        Book book = queryById(friendId);
        book.setShield(0);
        return update(book)!= null;
    }
}
